<html>
<head>
<script src="../../resources/js-test.js"></script>
<body>
    <div id="test">
        <input type="text">
        <textarea type="text"></textarea>
    </div>
    <div id="console"></div>
</body>
<script>

    if (window.testRunner)
        testRunner.dumpAsText();

    var events = [];

    var UPPER_CASE_T_KEY_CODE = 84;
    var LOWER_CASE_T_CHAR_CODE = 116;

    function keyListener(event)
    {
        if (event.keyCode == UPPER_CASE_T_KEY_CODE || event.keyCode == LOWER_CASE_T_CHAR_CODE) 
            event.preventDefault();
        event.target.value = event.target.value.replace('t', '');
    }
    
    function changeListener(event)
    {
        events.push(event.type + ' ' + event.target.value);
    }

    function sendKeysForString(target, str)
    {
        for (var i = 0; i < str.length; i++) {
            target.focus();
            eventSender.keyDown(str[i]);
            target.blur();
        }
    }

    // Replace value on keyup.
    var inputElement = document.body.getElementsByTagName('input')[0];
    inputElement.addEventListener('keyup', keyListener, false);
    inputElement.addEventListener('change', changeListener, false);

    if (window.eventSender)
        sendKeysForString(inputElement, 'test');

    shouldBe("events.length", "2");
    shouldBe("events[0]", "'change e'");
    shouldBe("events[1]", "'change es'");

    var textAreaElement = document.body.getElementsByTagName('textarea')[0];
    textAreaElement.addEventListener('keyup', keyListener, false);
    textAreaElement.addEventListener('change', changeListener, false);
    events.length = 0;

    if (window.eventSender)
        sendKeysForString(textAreaElement, 'atttbttc');

    shouldBe("events.length", "3");
    shouldBe("events[0]", "'change a'");
    shouldBe("events[1]", "'change ab'");
    shouldBe("events[2]", "'change abc'");


    // Prevent default on keydown.
    inputElement.removeEventListener('keyup', keyListener, false);
    inputElement.addEventListener('keydown', keyListener, false);
    inputElement.value = '';
    events.length = 0;

    if (window.eventSender)
        sendKeysForString(inputElement, 'test');

    shouldBe("events.length", "2");
    shouldBe("events[0]", "'change e'");
    shouldBe("events[1]", "'change es'");


    // Prevent default on keypress.
    inputElement.removeEventListener('keydown', keyListener, false);
    inputElement.addEventListener('keypress', keyListener, false);
    inputElement.value = '';
    events.length = 0;

    if (window.eventSender)
        sendKeysForString(inputElement, 'test');

    shouldBe("events.length", "2");
    shouldBe("events[0]", "'change e'");
    shouldBe("events[1]", "'change es'");
    
    // Hide test elements after run to avoid whitespace differences across platforms in the results.
    document.getElementById('test').style.display = 'none';
</script>
</html> 

